﻿using System;
using System.Collections.Generic;
using System.Linq;
using Vms.Web.Models;
using System.Data;
using Vms.Web.Lib;
using Vms.Web.Services;
using System.IO;
using System.Text;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using Vms.Web.Services.Rrf;


namespace Vms.Web.Controllers
{
    public class ContentProgramController : Controller
    {
        //
        // GET: /ContentProgram/
        private VmsWebContext vmsDB = new VmsWebContext();
        // 20/3/2013: Tung create DB connect
        private char[] separatorDate = { '/' };
        private char[] separatorTime = { ':' };

        public ActionResult Index(int screenId = -1, int progId = -1)
        {
            //BoardServices boardService = BoardServices.CreateBoardService();

            List<SCREEN> screens = vmsDB.SCREENS.ToList();
            ViewBag.Screens = screens;
            SCREEN currentScreen = null; 

            if (screenId == -1)
            {
                if (screens.Count != 0)
                {
                    currentScreen = screens.First();
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                currentScreen = screens.Single(s => s.Id == screenId);
            }
            ViewBag.CurrentScreen = currentScreen;
            PROGRAM program = new PROGRAM();
            
            #region INIT_DROP_DOWN_LIST_DATA

            // Font_Color
            List<SelectListItem> fontColors = new List<SelectListItem>();
            for (int i = 0; i < Utility.FONT_COLOR.GetLength(0); ++i)
            {
                SelectListItem item = new SelectListItem();
                item.Text = (string)Utility.FONT_COLOR[i, 0];
                item.Value = "" + Utility.FONT_COLOR[i, 1];
                fontColors.Add(item);
            }
            ViewBag.FontColors = fontColors;

            // Font_Name
            List<SelectListItem> fontNames = new List<SelectListItem>();
            for (int i = 0; i < Utility.FONT_NAME.Length; ++i)
            {
                SelectListItem item = new SelectListItem();
                item.Text = Utility.FONT_NAME[i];
                item.Value = Utility.FONT_NAME[i];
                fontNames.Add(item);
            }
            ViewBag.FontNames = fontNames;

            // Display Mode
            var displayMode = new List<object>();
            for (int i = 0; i < Utility.DISPLAY_MODE.GetLength(0); ++i)
            {
                var item = new
                {
                    Text = Utility.DISPLAY_MODE[i, 0],
                    Value = Utility.DISPLAY_MODE[i, 1]
                };
                displayMode.Add(item);
            }
            ViewBag.DisplayMode = displayMode;

            // Speeds
            var speeds = new List<object>();
            for (int i = 0; i < 64; ++i)
            {
                var item = new {
                    Text = i,
                    Value = i
                };
                speeds.Add(item);
            }
            ViewBag.Speeds = speeds;

            #endregion
           
            if (progId != -1)   // Edit program
            {
                program = vmsDB.PROGRAMS.Single(p => p.Id == progId);
                ViewBag.ProgId = program.Id;
                return View(program);
            }
            else
            {
                //program.SCREEN = currentScreen;
                //CONTENT content = new CONTENT();
                //CONTENT_IMG c_img = new CONTENT_IMG();
                //CONTENT_TXT c_txt = new CONTENT_TXT();
                //content.CONTENT_IMG.Add(c_img);
                //content.CONTENT_TXT.Add(c_txt);
            }
            return View(program);
        }

        [HttpPost]
        public ActionResult CreateProgram(PROGRAM program)
        {
            
            if (ModelState.IsValid)
            {
                CONTENT_IMG contentImg = new CONTENT_IMG();
                CONTENT_TXT contentTxt = new CONTENT_TXT();

                string file = "txt_" + DateTime.Now.Ticks + ".txt";
                System.IO.File.CreateText(Utility.PathScreenContentTxt + file);
                contentTxt.TxtFileName = file;
                GetDateTime(program);
                CONTENT content = new CONTENT();
                content.CONTENT_IMG.Add(contentImg);
                content.CONTENT_TXT.Add(contentTxt);
                program.CONTENTS.Add(content);
                vmsDB.PROGRAMS.Add(program);
                vmsDB.SaveChanges();
                return RedirectToAction("Index");
                
            }
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult EditProgram(PROGRAM program)
        {
            if (ModelState.IsValid)
            {

                GetDateTime(program);
                vmsDB.Entry(program).State = EntityState.Modified;
                
                vmsDB.SaveChanges();
                return RedirectToAction("Index");
            }
            return RedirectToAction("Index");
        }

        public ActionResult DeleteProgram(int programId)
        {
            PROGRAM program = vmsDB.PROGRAMS.Single(p => p.Id == programId);

            vmsDB.PROGRAMS.Remove(program);
            vmsDB.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult CreateImage(CONTENT_IMG image)
        {
            if (ModelState.IsValid)
            {
                image.DisplayMode = int.Parse(Request.Form.GetValues("DisplayMode")[0]);
                vmsDB.CONTENT_IMG.Add(image);
                vmsDB.SaveChanges();
                return RedirectToAction("Index");
            }
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Edit content image in content program.
        /// </summary>
        /// <param name="content_img"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditImage(CONTENT_IMG content_img)
        {
            if (ModelState.IsValid)
            {
            content_img.DisplayMode = int.Parse(Request.Form.GetValues("DisplayMode")[0]);
            vmsDB.Entry(content_img).State = EntityState.Modified;
            
            vmsDB.SaveChanges();
            return RedirectToAction("Index");
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult WordPad()
        {
            return View("WordPad");
        }

        /// <summary>
        /// Edit content text in content program
        /// </summary>
        /// <param name="content_txt"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditText(CONTENT_TXT content_txt)
        {
            if (ModelState.IsValid)
            {
            vmsDB.Entry(content_txt).State = EntityState.Modified;
            string file = Utility.PathScreenContentTxt + content_txt.TxtFileName;

            if (System.IO.File.Exists(file))
            {
                System.IO.StreamWriter sw = System.IO.File.CreateText(file);
                sw.Write(content_txt.Txt);
                sw.Close();
            }
            else
            {
                file = "txt_" + DateTime.Now.Ticks + ".txt";
                System.IO.StreamWriter sw = System.IO.File.CreateText(file);
                sw.Write(content_txt.Txt);
                sw.Close();
                content_txt.TxtFileName = file;
            }
            string txt = content_txt.Txt;
            content_txt.DisplayMode = int.Parse(Request.Form.GetValues("DisplayMode")[0]);
            vmsDB.SaveChanges();
                return RedirectToAction("Index");
            }
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult EditContent(string text)//FormCollection collection)
        {
            JObject jcontent_program = JObject.Parse(text);
            int program_id = (int)jcontent_program["content_programs"]["program_id"];
            CONTENT content = vmsDB.CONTENTS.Where(c => c.Program_Id == program_id).First();
            // Delete exist content texts and images.
            List<CONTENT_TXT> content_txts = content.CONTENT_TXT.ToList();
            if (content_txts != null)
            {
                foreach (var txt in content_txts)
                {
                    if (txt.TxtFileName.EndsWith(".rtf"))
                    {
                        string file = Utility.PathScreenContentTxt + txt.TxtFileName;
                        DeleteFile(file);
                    }
                    vmsDB.CONTENT_TXT.Remove(txt);
                }
                vmsDB.SaveChanges();
            }
            // create new content texts and images
            JArray jcontent = (JArray)jcontent_program["content_programs"]["contents"];
            foreach (var json in jcontent)
            {
                int y = (int)json["y"];
                int x = (int)json["x"];
                int width = (int)json["width"];
                int height = (int)json["height"];
                string txt = (string)json["text"];
                int font_size = (int)json["font_size"];
                string font_family = (string)json["font_family"];
                bool bold = (bool)json["bold"];
                string txt_color = (string)json["color"];
                int color = ToColor(txt_color);
                string img = (string)json["img"];
                int begin = img.IndexOf("/Imgs/");
                if (begin != -1)
                {
                    img = img.Substring(begin + "/Imgs/".Length);
                }
                int speed = (int)json["run_speed"];
                int method = (int)json["display_mode"];
                int showtime = (int)json["show_time"];
                int showsingle = (int)json["show_single"];
                //
                CONTENT_TXT content_txt = new CONTENT_TXT();
                content_txt.Txt_x = x;
                content_txt.Txt_y = y;
                content_txt.Txt_Width = width;
                content_txt.Txt_Height = height;
                content_txt.Txt = txt;
                content_txt.FontSize = font_size;
                content_txt.FontName = font_family;
                content_txt.Bold = bold;
                content_txt.FontColor = color;
                if (img.Equals(""))
                {
                    string file = "txt_" + DateTime.Now.Ticks + ".rtf";
                    CreateFile(file, RtfUtility.createRtfDocument(font_size, bold, font_family, txt_color, txt));
                    content_txt.TxtFileName = file;
                }
                else
                {
                    content_txt.TxtFileName = img;
                }
                content_txt.ShowSingleLine = 1;
                content_txt.RunSpeed = speed;
                content_txt.ShowTime = showtime;
                content_txt.DisplayMode = method;
                content_txt.ShowSingleLine = showsingle;
                content_txt.CONTENT = content;
                content_txt.Content_Id = content.Id;
                vmsDB.CONTENT_TXT.Add(content_txt);
            }
            vmsDB.SaveChanges();
            if (ModelState.IsValid)
            {
                // Update content
            //    int id = int.Parse(collection["Content_ID"]);
            //    string json = collection["Content_Name"];
            //    CONTENT content = vmsDB.CONTENTS.Single(c => c.Id == id);
            //    vmsDB.Entry(content).State = EntityState.Modified;
            //    content.Name = collection["Content_Name"];
            //    // Update Content Img
            //    int img_id = int.Parse(collection["Img_ID"]);
            //    CONTENT_IMG content_img = content.CONTENT_IMG.Single(img=>img.Id == img_id);
            //    vmsDB.Entry(content_img).State = EntityState.Modified;

            //    content_img.Img_Height = int.Parse(collection["Img_Height"]);
            //    content_img.Img_Width = int.Parse(collection["Img_Width"]);
            //    content_img.Img_x = int.Parse(collection["Img_x"]);
            //    content_img.Img_y = int.Parse(collection["Img_y"]);
            //    content_img.RunSpeed = int.Parse(collection["Img_RunSpeed"]);
            //    content_img.DisplayMode = int.Parse(collection["Img_DisplayMode"]);
            //    content_img.ImgFileName = collection["ImgFileName"];

            //    // Update Content txt
            //    int txt_id = int.Parse(collection["Txt_ID"]);
            //    CONTENT_TXT content_txt = content.CONTENT_TXT.Single(txt => txt.Id == txt_id);
            //    vmsDB.Entry(content_txt).State = EntityState.Modified;

            //    content_txt.Txt = collection["Txt"];
            //    content_txt.Txt_Height = int.Parse(collection["Txt_Height"]);
            //    content_txt.Txt_Width = int.Parse(collection["Txt_Width"]);
            //    content_txt.Txt_x = int.Parse(collection["Txt_x"]);
            //    content_txt.Txt_y = int.Parse(collection["Txt_y"]);
            //    content_txt.RunSpeed = int.Parse(collection["Txt_RunSpeed"]);
            //    content_txt.DisplayMode = int.Parse(collection["Txt_DisplayMode"]);
            //    content_txt.FontName = collection["FontName"];
            //    content_txt.FontSize = int.Parse(collection["FontSize"]);
            //    content_txt.FontColor = int.Parse(collection["FontColor"]);
            //    string b = collection["Bold"];
            //    content_txt.Bold = ("on".Equals(collection["Bold"])) ? true : false;

            //    string file = Utility.PathScreenContentTxt + content_txt.TxtFileName;

            //    if (System.IO.File.Exists(file))
            //    {
            //        System.IO.StreamWriter sw = System.IO.File.CreateText(file);
            //        sw.Write(content_txt.Txt);
            //        sw.Close();
            //    }
            //    else
            //    {
            //        file = "txt_" + DateTime.Now.Ticks + ".txt";
            //        System.IO.File.CreateText(file);
            //        content_txt.TxtFileName = file;
            //    }
                
            //    // Save update content
            //    vmsDB.SaveChanges();
            }
            return View();
        }

        //
        // GET: /ContentProgram/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /ContentProgram/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /ContentProgram/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /ContentProgram/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /ContentProgram/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // Load Library Image
        public ActionResult LibImage()
        {
            return PartialView(vmsDB.LIB_IMGS.ToList());
        }

        // Load Library Contents
        public ActionResult LibContents()
        {
            return PartialView(vmsDB.LIB_CONTENTS.ToList());
        }

        //
        // GET: /ContentProgram/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /ContentProgram/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // 20/3/2013 : Tung overtide Dispose
        protected override void Dispose(bool disposing)
        {
            if (vmsDB != null)
            {
                vmsDB.Dispose();
            }
            base.Dispose(disposing);
        }

        // Get date and time from form html
        private void GetDateTime(PROGRAM program)
        {
            string endaging = Request.Form.GetValues("EndAging")[0];
            if (endaging != null)
            {
                string[] date1 = endaging.Split(separatorDate, StringSplitOptions.RemoveEmptyEntries);
                if (date1.Length != 0)
                {
                    program.EndDay = int.Parse(date1[1]);
                    program.EndMonth = int.Parse(date1[0]);
                    program.EndYear = int.Parse(date1[2]);
                }
            }
            //
            string startaging = Request.Form.GetValues("StartAging")[0];
            if (startaging != null)
            {
                string[] date2 = startaging.Split(separatorDate, StringSplitOptions.RemoveEmptyEntries);
                if (date2.Length != 0)
                {
                    program.StartDay = int.Parse(date2[1]);
                    program.StartMonth = int.Parse(date2[0]);
                    program.StartYear = int.Parse(date2[2]);
                }
            }
            //
            string starttime = Request.Form.GetValues("StartTime")[0];
            if (starttime != null)
            {
                string[] time1 = starttime.Split(separatorTime, StringSplitOptions.RemoveEmptyEntries);
                if (time1.Length != 0)
                {
                    program.StartMinute = int.Parse(time1[1]);
                    program.StartHour = int.Parse(time1[0]);
                }
            }
            //
            string endtime = Request.Form.GetValues("EndTime")[0];
            if (endtime != null)
            {
                string[] time2 = endtime.Split(separatorTime, StringSplitOptions.RemoveEmptyEntries);
                if (time2.Length != 0)
                {
                    program.EndMinute = int.Parse(time2[1]);
                    program.EndHour = int.Parse(time2[0]);
                }
            }
        }

        private int ToColor(string rgb)
        {
            if (rgb.Equals("rgb(255, 255, 255)"))
            {
                return 7;
            }
            if (rgb.Equals("rgb(255, 0, 0)"))
            {
                return 1;
            }
            if (rgb.Equals("rgb(0, 128, 0)"))
            {
                return 2;
            }
            if (rgb.Equals("rgb(255, 255, 0)"))
            {
                return 3;
            }
            if (rgb.Equals("rgb(0, 0, 255)"))
            {
                return 4;
            }
            return 0;
        }

        private void CreateFile(string fileName, string content)
        {
            System.IO.StreamWriter sw = System.IO.File.CreateText(Utility.PathScreenContentTxt + fileName);
            sw.Write(content);
            sw.Close();
        }

        private void DeleteFile(string fileName)
        {
            System.IO.File.Delete(fileName);
        }

    }
}
